clear *

use "${root}/data/processed/final_sample.dta", clear

keep if baseline_sample == 1

* Using party weights from the same electoral cycle

gen left_ideology=.
gen nonleft_ideology=.

replace left_ideology=rank_1_coalition_ideo if rank_1_mayor_left==1
replace nonleft_ideology=rank_1_coalition_ideo if rank_1_mayor_left==0

forvalues i = 1(1)13 {
	replace left_ideology=rank_`i'_coalition_ideo if left_ideology==. & rank_1_mayor_left==0 & rank_best_opposition==`i'
	replace nonleft_ideology=rank_`i'_coalition_ideo if nonleft_ideology==. & rank_1_mayor_left==1 & rank_best_opposition==`i'
	}
	
gen distance = nonleft_ideology - left_ideology

sum distance, detail
sum coalition_ideo_dist, detail

reg distance coalition_ideo_dist

count if distance>0
count if distance<0

count if coalition_ideo_dist>0
count if coalition_ideo_dist<0


* Using party weights from the previous electoral cycle

gen left_ideology_lagw=.
gen nonleft_ideology_lagw=.

replace left_ideology_lagw=rank_1_coalition_ideo_lagw if rank_1_mayor_left==1
replace nonleft_ideology_lagw=rank_1_coalition_ideo_lagw if rank_1_mayor_left==0

forvalues i = 1(1)13 {
	replace left_ideology_lagw=rank_`i'_coalition_ideo_lagw if left_ideology_lagw==. & rank_1_mayor_left==0 & rank_best_opposition==`i'
	replace nonleft_ideology_lagw=rank_`i'_coalition_ideo_lagw if nonleft_ideology_lagw==. & rank_1_mayor_left==1 & rank_best_opposition==`i'
	}
	
gen distance_lagw = nonleft_ideology_lagw - left_ideology_lagw
sum distance_lagw, detail

sum coalition_ideo_dist_lagw, detail

reg distance_lagw coalition_ideo_dist_lagw

count if distance_lagw>0
count if distance_lagw<0

count if coalition_ideo_dist_lagw>0
count if coalition_ideo_dist_lagw<0


* Test for a jump in ideology at the threshold
rdrobust rank_1_coalition_ideo_lagw margin_mayor_left if baseline_sample==1, vce(cluster mun_code) all 

* call program to make rd graphs
do "${root}/codes/analysis/programs/rdgraph_prog.do"

set scheme plotplain

rdgraph rank_1_coalition_ideo_lagw margin_mayor_left, title("RD Plot - ideology of the mayor's coalition") name(tot_exp_avg_pc) ytitle("Mayor's coalition ideology score") xtitle("Left margin of victory") pos(9) legend(yes)
graph export "${root}/results/figures/ideology_jump.pdf", replace
